package com.bskj.kuaifu.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.bskj.common.bean.model.CodeValue;
import com.bskj.common.bean.model.ParkInfo;
import com.bskj.common.bean.model.UserAppeal;
import com.bskj.common.bean.model.UserCar;
import com.bskj.common.bean.model.UserInfo;
import com.bskj.common.constants.CommonConstatns;
import com.bskj.common.enums.UserMoneyChangeTypeEnum;
import com.bskj.common.utils.EncryptUtil;
import com.bskj.common.utils.Global;
import com.bskj.common.utils.HttpRequestUtil;
import com.bskj.common.utils.LogUtils;
import com.bskj.common.utils.ResultMapUtil;
import com.bskj.common.utils.StringUtils;
import com.bskj.common.utils.WeixinApiUtils;
import com.bskj.common.web.BaseController;
import com.bskj.kuaifu.bean.vo.resp.ParkinfoAppealVo;
import com.bskj.kuaifu.bean.vo.resp.UserMoneyLogRespVo;
import com.bskj.kuaifu.bean.vo.resp.UserMyMoneyDetailRespVo;
import com.bskj.kuaifu.bean.vo.resp.UserUnPayDetailRespVo;
import com.bskj.kuaifu.service.IParkInfoService;
import com.bskj.kuaifu.service.IPayInfoService;
import com.bskj.kuaifu.service.IUserInfoService;
import com.bskj.kuaifu.service.IUserMoneyLogService;

/**
 * @author lishi
 * @date 2017-12-6 下午12:08:24
 */
@Controller
@RequestMapping("user")
public class UserInfoController extends BaseController {
    @Autowired
    private IUserInfoService userInfoService;

    @Autowired
    private IParkInfoService parkInfoService;

    @Autowired
    private IUserMoneyLogService userMoneyLogService;

    @Autowired
    private IPayInfoService payInfoService;

    @RequestMapping("recharge/unpayDetail")
    public ModelAndView unpayDetailIndex(int userId, String url) throws Exception {
        ModelAndView mv = new ModelAndView();
        mv.setViewName("/recharge/unpayDetail");
        mv.addObject("userId", userId);

        JSONObject signatureObj = WeixinApiUtils.jssdk_signture(url, CommonConstatns.KUAIFU_ACCOUNTID);
        mv.addObject("signature", signatureObj);

        JSONObject wxPayDtlParams = new JSONObject();
        wxPayDtlParams.put("uri", "/user/chargeUnpayDetail");
        String openId = getRequest().getParameter("openId");
        if (StringUtils.isBank(openId)) {
            UserInfo userInfo = userInfoService.get(userId);
            if (userInfo != null) {
                openId = userInfo.getOpenid();
            } else {
                throw new Exception("No openid was selected:" + userId);
            }
        }
        wxPayDtlParams.put("openId", openId);
        wxPayDtlParams.put("userId", userId);
        mv.addObject("wxPayDtlParams", EncryptUtil.encrypt(wxPayDtlParams.toJSONString()));

        unpayDetailParams(userId, mv);
        topupParams(userId, mv);

        return mv;
    }

    @RequestMapping("recharge/myMoney")
    public ModelAndView myMoneyIndex(Integer userId, String url) throws Exception {
        ModelAndView mv = new ModelAndView();
        mv.setViewName("/recharge/myMoney");
        mv.addObject("userId", userId);

        JSONObject signatureObj = WeixinApiUtils.jssdk_signture(url, CommonConstatns.KUAIFU_ACCOUNTID);
        mv.addObject("signature", signatureObj);

        myMoneyDetailParams(userId, mv);
        withdrawCashParams(userId, mv);
        //unpayDetailParams(userId, mv);
        topupParams(userId, mv);
        transDetailParams(userId, mv);

        JSONObject unpayDetailParams = new JSONObject();
        unpayDetailParams.put("uri", "/user/chargeUnpayDetail");
        String openId = getRequest().getParameter("openId");
        if (StringUtils.isBank(openId)) {
            UserInfo userInfo = userInfoService.get(userId);
            if (userInfo != null) {
                openId = userInfo.getOpenid();
            } else {
                throw new Exception("No openid was selected:" + userId);
            }
        }
        unpayDetailParams.put("openId", openId);
        unpayDetailParams.put("userId", userId);
        mv.addObject("unpayDetailParams", EncryptUtil.encrypt(unpayDetailParams.toJSONString()));

        return mv;
    }

    @RequestMapping("recharge/transDetail")
    public ModelAndView transDetailIndex(int userId) throws Exception {
        ModelAndView mv = new ModelAndView();
        mv.setViewName("/recharge/transDetail");
        mv.addObject("userId", userId);

        List<UserMoneyLogRespVo> delMoneyLogList = parkInfoService.getUserMoneyLog(userId,
                1, CommonConstatns.DEFAULT_PAGE_SZIE);
        mv.addObject("delMoneyLogList", delMoneyLogList);

        JSONObject toAppeal = new JSONObject();
        toAppeal.put("uri", "/user/toAppeal");
        toAppeal.put("userId", userId);
        mv.addObject("toAppeal", EncryptUtil.encrypt(toAppeal.toJSONString()));
        
        
        JSONObject transDetailDataParam = new JSONObject();
        transDetailDataParam.put("uri", "/user/getTransDetailData");
        transDetailDataParam.put("userId", userId);
        mv.addObject("transDetailDataParam", EncryptUtil.encrypt(transDetailDataParam.toJSONString()));
        return mv;
    }

    @RequestMapping("/recharge/topup")
    public ModelAndView topupIndex(int userId, String url) throws Exception {
        ModelAndView mv = new ModelAndView();
        mv.setViewName("/recharge/topup");
        mv.addObject("userId", userId);

        JSONObject signatureObj = WeixinApiUtils.jssdk_signture(url, CommonConstatns.KUAIFU_ACCOUNTID);
        mv.addObject("signature", signatureObj);

        JSONObject unifiedorderParams = new JSONObject();
        unifiedorderParams.put("uri", "/pay/unifiedorder");
        String openId = getRequest().getParameter("openId");
        if (StringUtils.isBank(openId)) {
            UserInfo userInfo = userInfoService.get(userId);
            if (userInfo != null) {
                openId = userInfo.getOpenid();
            } else {
                throw new Exception("No openid was selected:" + userId);
            }
        }
        unifiedorderParams.put("openId", openId);
        unifiedorderParams.put("userId", userId);
        mv.addObject("unifiedorderParams", EncryptUtil.encrypt(unifiedorderParams.toJSONString()));

        myMoneyParams(userId, mv);
        LogUtils.debug("url : " + url);
        LogUtils.debug("signature : " + signatureObj);
        return mv;
    }

    @RequestMapping("/recharge/withdrawCash")
    public ModelAndView withdrawCashIndex(int userId) throws Exception {
        ModelAndView mv = new ModelAndView();
        mv.setViewName("/recharge/withdrawCash");
        mv.addObject("userId", userId);
        UserInfo userInfo = userInfoService.get(userId);
        if (userInfo != null) {
            mv.addObject("userInfo", userInfo);
        }

        JSONObject withdrawCashParams = new JSONObject();
        withdrawCashParams.put("uri", "/user/withdrawCash");
        withdrawCashParams.put("userId", userId);
        mv.addObject("withdrawCashParams", EncryptUtil.encrypt(withdrawCashParams.toJSONString()));

        myMoneyParams(userId, mv);

        return mv;
    }

    /**
     * 微信支付 欠费订单
     *
     * @param appId
     * @param openId
     * @param userId
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("chargeUnpayDetail")
    public Map<String, Object> chargeUnpayDetail(String appId, String openId, Integer userId) throws Exception {
        Map<String, String> resultMap = null;
        UserUnPayDetailRespVo unpayDetail = parkInfoService.getUnPayDetail(userId);
        if (unpayDetail.getTotalFee() <= 0) {
            return ResultMapUtil.genErrorMap("金额为0,请联系管理员");
        }

        try {
            String ip = HttpRequestUtil.getIp(getRequest());
            String notifyUrl = Global.getConfig("WX_UNPAY_NOTIFY_URL");
            resultMap = payInfoService.unifiedOrder(appId, openId, userId, unpayDetail.getTotalFee(), ip, notifyUrl);
            if (StringUtils.isBank(resultMap.get("error"))) {
                return ResultMapUtil.genDefaultSuccessDataMap(resultMap.get("wxPayParams"));
            } else {
                return ResultMapUtil.genErrorMap(resultMap.get("error"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultMapUtil.genErrorMap("下单失败,请重试");
        }

    }

    /**
     * 微信支付 欠费订单
     *
     * @param appId
     * @param openId
     * @param userId
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("getUnpayDetail")
    public Map<String, Object> getUnpayDetail(String appId, String openId, Integer userId) throws Exception {
        UserUnPayDetailRespVo unpayDetail = parkInfoService.getUnPayDetail(userId);
        return ResultMapUtil.genResultMap(true, null, null, unpayDetail);
    }

    /**
     * 获取交易明细信息
     *
     * @param userId
     * @param type
     * @param page
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("getTransDetailData")
    public Map<String, Object> getTransDetailData(int userId, int type, Integer page) throws Exception {
        if (page == null || page == 0) {
            page = 1;
        }
        List<UserMoneyLogRespVo> moneyLogList = parkInfoService.getUserMoneyLog(userId, page,
                CommonConstatns.DEFAULT_PAGE_SZIE);
        return ResultMapUtil.genDefaultSuccessDataMap(moneyLogList);
    }

    @ResponseBody
    @RequestMapping("myMoneyDetail")
    public Map<String, Object> getMyMoneyDetail(Integer userId) throws Exception {
        UserMyMoneyDetailRespVo moneyDetail = userInfoService.getMyMoneyDetail(userId);
        return ResultMapUtil.genResultMap(true, null, null, moneyDetail);
    }

    
    
    @ResponseBody
    @RequestMapping("myCarNo")
    public ModelAndView getMyCarNo(Integer userId) throws Exception {
        ModelAndView mv = getRequestModelAndView();
        List<UserCar> userCars = userInfoService.getMyCarNo(userId);

        mv.addObject("userCars", userCars);
        mv.setViewName("/user/myCarNo");
        addMyCarNoParams(userId, mv);
        delMyCarNoParams(userId, mv);
        return mv;
    }

    @ResponseBody
    @RequestMapping("info")
    public ModelAndView info(Integer userId) throws Exception {
        ModelAndView mv = getRequestModelAndView();
        UserInfo userInfo = userInfoService.get(userId);
        String carNo = "";
        List<UserCar> userCars = userInfoService.getMyCarNo(userId);
        if (userCars != null && userCars.size() >= 1) {
            carNo = userCars.get(0).getCarNo();
        }

        mv.addObject("carNo", carNo);
        mv.addObject("userInfo", userInfo);

        registerParams(userId, mv);
        myMoneyParams(userId, mv);
        myCarNoParams(userId, mv);
        transDetailParams(userId, mv);

        LogUtils.debug(JSONObject.toJSONString(mv.getModel()));
        mv.setViewName("/user/center");
        return mv;
    }

    @ResponseBody
    @RequestMapping("guidline")
    public ModelAndView guidline(Integer userId) throws Exception {
        ModelAndView mv = getRequestModelAndView();

        topupParams(userId, mv);

        mv.setViewName("/user/guidline");
        return mv;
    }


    @ResponseBody
    @RequestMapping("withdrawCash")
    public Map<String, Object> withdrawCash(Integer userId) throws Exception {
        return userInfoService.withdrawCash(userId);
    }
    
    @RequestMapping("/toAppeal")
    public ModelAndView toAppeal(Integer pId,Integer userId) throws Exception{
    	ModelAndView mv=new ModelAndView();
    	ParkinfoAppealVo parkinfoAppealVo=parkInfoService.getParkinfoAppealVo(pId);
    	mv.addObject("parkinfoAppealVo", parkinfoAppealVo);
    	List<CodeValue> codeValues=userInfoService.findAppealType();
    	mv.addObject("codeValues", codeValues);
    	mv.setViewName("/user/appeal");
    	
    	JSONObject appeal = new JSONObject();
        appeal.put("uri", "/user/appeal");
        appeal.put("userId", userId);
        appeal.put("parkinfoId", pId);
        mv.addObject("appealParams", EncryptUtil.encrypt(appeal.toJSONString()));
    	
        JSONObject success = new JSONObject();
        success.put("uri", "/user/success");
        success.put("userId", userId);
        mv.addObject("successParams", EncryptUtil.encrypt(success.toJSONString()));
        
    	return mv;
    }
    
    @RequestMapping("/success")
    public ModelAndView toSuccess() {
    	ModelAndView mv=new ModelAndView();
    	mv.setViewName("/user/ok");
    	return mv;
	}
    
    @ResponseBody
    @RequestMapping("/appeal")
    public Map<String, Object> appeal(UserAppeal userAppeal,Integer userId) throws Exception{
    	Map<String, Object> resultMap=new HashMap<>();
    	userInfoService.insertAppeal(userAppeal);
    	resultMap.put("result",true );
    	return resultMap;
	}
    
    @RequestMapping("/block")
    public ModelAndView toBlock() {
    	ModelAndView mv=new ModelAndView();
    	mv.setViewName("/user/block");
    	return mv;
	}
    
    @RequestMapping("/nono")
    public ModelAndView toNono() {
    	ModelAndView mv=new ModelAndView();
    	mv.setViewName("/user/nono");
    	return mv;
	}
}
